﻿using SAICAPPWEB.BLL;
using SAICAPPWEB.Models;
using SAICAPPWEB.Service;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace SAICAPPWEB.Common
{
    /// <summary>
    /// Summary description for Login
    /// </summary>
    public class LoginBll 
    {

     

        private bool CheckDomainUser(string path, string userName, string userPassword)
        {

            DirectoryEntry entry = new DirectoryEntry(path, userName, userPassword);
            try
            {
                object obj = entry.NativeObject;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public bool CheckDomainUser(string account, string userPassword)
        {
            string path = System.Configuration.ConfigurationManager.AppSettings["DomainString"];
            List<string> domainPaths = Parse(path);
            foreach (string domainPath in domainPaths)
            {
                bool result = CheckDomainUser(domainPath, account, userPassword);
                if (result)
                {
                    return true;
                }
            }
            return false;
        }

        private List<string> Parse(string path)
        {

            List<string> ipAddresses = new List<string>();
            string[] domainPaths = path.Split(';');
            foreach (string domainPath in domainPaths)
            {
                int startIndex = domainPath.IndexOf("//");
                int endIndex = domainPath.IndexOf("\\");
                string ip = domainPath.Substring(startIndex + 2, endIndex - (startIndex + 2));
                string domainDC = domainPath.Substring(endIndex + 1);
                string[] ips = ip.Split('-');
                foreach (string ipAddress in ips)
                {
                    ipAddresses.Add("LDAP://" + ipAddress + "/" + domainDC);
                }
            }
            return ipAddresses;
        }

   
    }
}